const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: 0,
    tab: 0,
    _ip: "http://www.mmdccj.top:9003",
    image: null,
    // 背景色
    nowRGBA: null,
    // 字体色
    nowRGB: null,
    // 播放状态
    state: null,
    keyword: '',
    // 播放列表数据
    list: [],
    musiclist: null,
    dataId: '0',
    play: null,
    page: 'main',
    userId: null
  },
  // 加载时
  onLoad() {
    const ip = this.data._ip
    // 获取推荐歌单
    wx.request({
      url: ip + '/musicList/getList',
      success: res => {
        this.setData({
          'musiclist': res.data.data
        })
        for (let i = 0; i < this.data.musiclist.length; i++) {
          let data = `musiclist[${i}].image`
          this.setData({
            [data]: 'http://www.mmdccj.top:9003/static/image/' + this.data.musiclist[i].image
          })
        }
      }
    })
    // 监听播放进度
    app.globalData.audioCtx.onTimeUpdate(() => {
      app.globalData.play.duration = app.formatTime(app.globalData.audioCtx.duration)
      app.globalData.play.currentTime = app.formatTime(app.globalData.audioCtx.currentTime)
      app.globalData.play.percent = app.globalData.audioCtx.currentTime / app.globalData.audioCtx.duration * 100
      this.setData({
        ['play.duration']: app.globalData.play.duration,
        ['play.currentTime']: app.globalData.play.currentTime,
        ['play.percent']: app.globalData.play.percent,
      })
    })
  },
  // 删除播放列表
  popMusic: function (e) {
    app.popMusic(e.currentTarget.dataset.index);
    this.onReady()
    console.log("pop");
  },
  // 去评论页
  toComment: function () {
    if (this.data.play.playMusicId != null) {
      wx.navigateTo({
        url: `/pages/comment/comment?id=${this.data.play.playMusicId}&type=m&image=${this.data.play.coverImgUrl}&title=${this.data.play.title}&user=${this.data.play.singer}`,
      })
    } else {
      wx.showToast({
        title: '当前播放为空',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    }
  },

  // 去评论页
  toComment: function () {
    if (this.data.play.playMusicId != null) {
      wx.navigateTo({
        url: `/pages/comment/comment?id=${this.data.play.playMusicId}&type=m&image=${this.data.play.coverImgUrl}&title=${this.data.play.title}&user=${this.data.play.singer}`,
      })
    } else {
      wx.showToast({
        title: '当前播放为空',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    }
  },
  // 去个人中心
  toPersonCenter: function () {
    this.setData({
      page: 'personCenter',
      userId: '1' // 恢复用户id
    })
  },
  // 最多播放
  toMostLikeMusic: function () {
    this.setData({
      page: 'mostLike'
    })
  },
  // 去船新音乐
  toNewMusic: function () {
    this.setData({
      page: 'new'
    })
  },
  changePage: function (e) {
    this.setData({
      page: e.detail
    })
  },
  changeDataId: function (e) {
    console.log("更改歌单id",e.detail);
    this.setData({
      dataId: e.detail
    })
  },
  // 去到搜索页
  gotoSearch: function () {
    console.log(this.data.keyword);
    if (this.data.keyword == '') return
    // wx.navigateTo({
    //     url: '/pages/search/search?keyword=' + this.data.keyword,
    // })
    this.setData({
      page: 'search'
    })
  },
  // 与input实现双向数据绑定
  inputChange: function (e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  changePage: function (e) {
    this.setData({
      page: e.detail
    })
  },
  changeUserId: function (e) {
    this.setData({
      userId: e.detail
    })
    
  },
  

  // 页面切换
  changeItem: function (e) {
    console.log("======>", e.target.dataset.item)
    this.setData({
      item: e.target.dataset.item,
      tab: e.target.dataset.item,
      page: 'main'
    })
  },

  // tab切换
  changeTab: function (e) {
    console.log("==ChangeTab====>", e.detail.current)
    this.setData({
      tab: e.detail.current,
    })
  },

  // 去歌单页面
  toListPage: function (e) {
    this.setData({
      dataId: this.data.musiclist[e?.currentTarget?.dataset.listid].id,
    })
    this.setData({
      page: 'list'
    })
  },
  // 去CD页面
  toCDListPage:function(){
    this.setData({
      dataId: this.data.musiclist[e?.currentTarget?.dataset.listid].id,
    })
    this.setData({
      page: 'list'
    })
  },
  sliderChange: function (e) {
    app.sliderChange(e)
    this.onReady()
  },

  play: function () {
    app.play()
    this.onReady()
    this.data.state = "playing"
  },
  pause: function () {
    app.pause()
    this.onReady()
    this.data.state = "paused"
  },
  next: function () {
    if (app.globalData.playlist.length == 0) {
      return
    }
    console.log("next");
    wx.showLoading({
      title: '加载中',
    })
    app.next()
    this.onReady()
    this.data.state = "playing"
  },
  // 播放列表换曲功能
  change: function (e) {
    wx.showLoading({
      title: '加载中',
    })
    app.updateMusic(e.currentTarget.dataset.index)
    app.globalData.audioCtx.onCanplay(() => {
      app.play()
      this.onReady()
      wx.hideLoading()
    })

  },
  onReady: function () {
    // 获取数据
    if (this.data.play != app.globalData.play) {
      this.setData({
        play: app.globalData.play
      })
    }
    if (this.data.state != app.globalData.state) {
      this.setData({
        state: app.globalData.state
      })
    }
    if (this.data.list != app.globalData.list) {
      this.setData({
        list: app.globalData.playlist
      })
    }
    if (!this.data.query) {
      let query = wx.createSelectorQuery().select('#myCanvas')
      setTimeout(() => {
        query.fields({
          node: true,
          size: true
        }).exec((res) => {
          // Canvas 对象
          const canvas = res[0].node
          // 渲染上下文
          const ctx = canvas.getContext('2d')
          const dpr = wx.getWindowInfo().pixelRatio
          // canvas的宽高
          canvas.width = 1295 * dpr
          canvas.height = 1295 * dpr
          ctx.scale(dpr, dpr)
          // 图片对象
          const image = canvas.createImage()
          console.log("image对象", image);
          image.onload = () => {
            // 绘制
            ctx.drawImage(this.data.image, 0, 0)
            // 获取像素
            let pxArr = ctx.getImageData(0, 0, 400, 400).data;
            pxArr = Array.from(pxArr);
            const colorList = {}
            let i = 0;
            while (i < pxArr.length) {
              const r = pxArr[i];
              const g = pxArr[i + 1];
              const b = pxArr[i + 2];
              const a = pxArr[i + 3];
              i = i + 4; // 最后 +4 比每次 i++ 快 10ms 左右性能
              const key = [r, g, b, a].join(',')
              key in colorList ? ++colorList[key] : (colorList[key] = 1)
            }
            let arr = [];
            for (let key in colorList) {
              const rgb = key.split(',', 3)
              rgb[0] = 255 - rgb[0]
              rgb[1] = 255 - rgb[1]
              rgb[2] = 255 - rgb[2]
              arr.push({
                rgba: `rgba(${key})`,
                // rgb: `rgb(${key.split(',',3)})`,
                rgb: `rgb(${rgb})`,
                num: colorList[key]
              })
            }
            arr = arr.sort((a, b) => b.num - a.num)
            console.log("图像arr", arr);
            this.setData({
              nowRGBA: arr[1].rgba,
            })
            ctx.clearRect(0, 0, 1295, 1295);
          }
          this.setData({
            image: image
          })
        })
        this.setData({
          query
        })
      }, 300);

    } else {
      this.getNewColor()
    }
  },
  updateDate: function () {
    this.onReady()
  },
  getNewColor: function () {
    console.log("setting img", this.data.play.coverImgUrl);
    let image = this.data.image
    if(image.src == this.data.play.coverImgUrl){
      return
    }
    image.src = this.data.play.coverImgUrl
    this.setData({
      image: image
    })
  },

})